from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys

sys.path.append("../")

from ui.Ui_upper_car_widget import Ui_UpperCarWidget
from common.utils import *
from drivers.driver_serial import*

class UpperCarWidget(QWidget):
    def __init__(self,parent:QMainWindow=None):
        super().__init__(parent)
        self.root_parent = parent
        self.ui = Ui_UpperCarWidget()
        self.ui.setupUi(self)
        # self.parent =
        self.current_serial_dev = None

        self.init_ui()
    def __show_status(self,msg,msecs=0):
        # parent:QMainWindow = self.root_parent
        if self.root_parent is None:
            return
        if not isinstance(self.root_parent, QMainWindow):
            return
        self.root_parent.statusBar().showMessage(msg, msecs)
    @pyqtSlot()
    def on_btn_connect_clicked(self):
        """连接设备时判断当前串口设备是否为空，为空则连接，不为空则断开连接
        1.获取当前选中设备
        2.获取波特率
        3.连接设备
        """
        if self.current_serial_dev is not None:
            #更改按钮将其设置为连接
            self.ui.btn_connect.setText("连接")
            self.current_serial_dev.close()
            self.current_serial_dev = None
            return
        # 获取当前选中的设备device
        current_dev = self.ui.cb_devices.currentData()
        # 获取波特率
        current_bandrate = self.ui.cb_bandrate.currentText()
        print("当前设备{}，波特率{}".format(current_dev,current_bandrate))
        if current_dev is None:
            self.__show_status("未扫描到串口设备请连接后再尝试",2000)
            return
        #已经是str类型不需要加""
        sp = SerialDevice(current_dev,int(current_bandrate),timeout=1)
        success, msg = sp.open()
        if success:
            print("串口设备已打开")
            self.__show_status("串口设备已打开{}".format(current_dev))
            #更新按钮文字
            self.ui.btn_connect.setText("断开连接")
            #sp.write(b"Hello, Serial!")  # 发送数据
            #print(sp.read(10))  # 读取10个字节的数据
            #将连接成功是当前串口设备不为空
            self.current_serial_dev = sp
            sp.close()
        else:
            self.__show_status("串口打开失败",2000)
            print(msg)

    def refresh_device(self):
        self.ui.cb_devices.clear()
        serial_ports = scan_serial_ports()
        if len(serial_ports) == 0:
            self.__show_status("未发现设备",2000)
            print("串口未连接")
            return
        self.__show_status("发现[{}]设备".format(len(serial_ports)))
        for device, description in serial_ports:
            print(device, "---", description)
        self.ui.cb_devices.addItem(description,userData=device)

    @pyqtSlot()
    def on_btn_refresh_clicked(self):    

        self.refresh_device()

    def init_ui(self):
        self.refresh_device()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = UpperCarWidget()
    window.show()
    sys.exit(app.exec_())
